package com.ruoyi.consumer.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.consumer.domain.CCar;
import com.ruoyi.consumer.domain.CUser;
import com.ruoyi.consumer.domain.car.CarInfoElement;
import com.ruoyi.consumer.domain.car.CarInfoJson;
import com.ruoyi.consumer.service.impl.CCarServiceImpl;
import com.ruoyi.consumer.service.impl.CUserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "车辆管理")
@RestController
@RequestMapping("/api/carInfo")
public class CarInfoController {

    @Autowired
    private CCarServiceImpl carService;

    @Autowired
    private CUserServiceImpl userService;

    @ApiOperation("上传车辆信息")
    @PostMapping("/upCarInfo")
    public AjaxResult upCarInfo(@RequestBody CarInfoJson carInfoJson) {
        Integer userId = carInfoJson.getUserid();
        CUser cUser = userService.selectCUserByUserId(userId);
        //用户不存在直接返回
        if (cUser == null || cUser.getCarId() == null) {
            return AjaxResult.error("用户不存在");
        }

        List<CarInfoElement> carInfoElementList = carInfoJson.getCarInfoElements();
        System.out.println(carInfoElementList);
        Map<String, Object> map = new HashMap<>();
        for (CarInfoElement carInfoElement : carInfoElementList) {
            map.put(carInfoElement.getKey(), carInfoElement.getValue());
        }

        //判断是否缺少必要字段
        if (map.get("plate_num").toString().isEmpty() || map.get("model").toString().isEmpty()) {
            return AjaxResult.success("缺少必要信息");
        }

        //处理发证日期,注册日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date issue_date_ = null;
        Date register_date_ = null;
        try {
            issue_date_ = dateFormat.parse(map.getOrDefault("issue_date", "").toString());
            register_date_ = dateFormat.parse(map.getOrDefault("register_date", "").toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        CCar cCar = new CCar();
        cCar.setPlateNum(map.get("plate_num").toString());

        //查询是否已经创建车辆信息
        List<CCar> cars = carService.selectCCarList(cCar);
        //cars为空说明没有创建车辆信息
        cCar.setModel(map.get("model").toString());
        //存入行驶证正反面
        cCar.setPermit(carInfoJson.getPermit());
        cCar.setPermitB(carInfoJson.getPermit_b());
        //存入格式化后的日期
        cCar.setRegisterDate(register_date_);
        cCar.setIssueDate(issue_date_);
        cCar.setPlateNum(map.getOrDefault("plate_num", "").toString());
        cCar.setModel(map.getOrDefault("model", "").toString());
        cCar.setOwner(map.getOrDefault("owner", "").toString());
        cCar.setVin(map.getOrDefault("vin", "").toString());
        cCar.setAddr(map.getOrDefault("addr", "").toString());
        cCar.setVehicleType(map.getOrDefault("vehicle_type", "").toString());
        cCar.setEngineNum(map.getOrDefault("engine_num", "").toString());
        cCar.setOfficialSeal(map.getOrDefault("official_seal", "").toString());
        cCar.setTotalQuality(map.getOrDefault("total_quality", "").toString());
        cCar.setUseCharacter(map.getOrDefault("use_character", "").toString());
        cCar.setLeadQuality(map.getOrDefault("lead_quality", "").toString());
        cCar.setOverallSize(map.getOrDefault("overall_size", "").toString());
        cCar.setPassengersNum(map.getOrDefault("passengers_num", "").toString());
        cCar.setPrepareQuality(map.getOrDefault("prepare_quality", "").toString());
        cCar.setRecord(map.getOrDefault("record", "").toString());
        cCar.setRemarks(map.getOrDefault("remarks", "").toString());
        cCar.setAxleCount(map.getOrDefault("axle_count", "").toString());
        cCar.setLoadQuality(map.getOrDefault("load_quality", "").toString());
        cCar.setLoadCapacity(map.getOrDefault("load_capacity", "").toString());
        if (cars.size() == 0) {
            int i = carService.insertCCar(cCar);
            if (i > 0) {
                //插入个人车辆信息
                List<CCar> cCars = carService.selectCCarList(cCar);
                CCar InCar = cCars.get(0);
                Integer carId = InCar.getCarId();
                CUser cUserNew = userService.selectCUserByUserId(carInfoJson.getUserid());
                cUserNew.setCarId(carId);
                userService.updateCUser(cUserNew);
                return AjaxResult.success("创建成功");
            }
        } else {


            Integer carId1 = cars.get(0).getCarId();
            CUser cUser1 = new CUser();
            cUser1.setCarId(carId1);
            List<CUser> cUsers = userService.selectCUserList(cUser1);

            //未创建车辆信息
            if (cUser.getCarId() == 0) {
                int i = carService.insertCCar(cCar);
                if (i > 0) {
                    //插入个人车辆信息
                    List<CCar> cCars = carService.selectCCarList(cCar);
                    CCar InCar = cCars.get(0);
                    Integer carId = InCar.getCarId();
                    CUser cUserNew = userService.selectCUserByUserId(carInfoJson.getUserid());
                    cUserNew.setCarId(carId);
                    userService.updateCUser(cUserNew);
                    return AjaxResult.success("创建成功");
                }
            } else {
                if (cUsers.size() == 1) {
                    CUser cUserNew = userService.selectCUserByUserId(carInfoJson.getUserid());
                    cUserNew.setCarId(cars.get(0).getCarId());
                    userService.updateCUser(cUserNew);
                    return AjaxResult.success("创建成功");
                } else if (cUsers.size() > 1) {
                    return AjaxResult.error("车辆已经分配至两人!");
                }

                Integer carId = cUser.getCarId();
                cCar.setCarId(carId);
                int i = carService.updateCCar(cCar);
                if (i > 0) {
                    return AjaxResult.success("更新成功");
                }

            }

           /* if (cUsers.size() == 1) {
                CUser cUserNew = userService.selectCUserByUserId(carInfoJson.getUserid());
                cUserNew.setCarId(cars.get(0).getCarId());
                userService.updateCUser(cUserNew);
                return AjaxResult.success("创建成功");
            } else if (cUsers.size() > 1) {
                return AjaxResult.error("车辆已经分配至两人!");
            }*/
        }

       /* //未创建车辆信息
        if (cUser.getCarId() == 0) {
            int i = carService.insertCCar(cCar);
            if (i > 0) {
                //插入个人车辆信息
                List<CCar> cCars = carService.selectCCarList(cCar);
                CCar InCar = cCars.get(0);
                Integer carId = InCar.getCarId();
                CUser cUserNew = userService.selectCUserByUserId(carInfoJson.getUserid());
                cUserNew.setCarId(carId);
                userService.updateCUser(cUserNew);
                return AjaxResult.success("创建成功");
            }
        } else {
            Integer carId = cUser.getCarId();
            cCar.setCarId(carId);
            int i = carService.updateCCar(cCar);
            if (i > 0) {
                return AjaxResult.success("更新成功");
            }

        }*/



/*        cCar.setModel(map.get("model").toString());
        //存入行驶证正反面
        cCar.setPermit(carInfoJson.getPermit());
        cCar.setPermitB(carInfoJson.getPermit_b());
        //存入格式化后的日期
        cCar.setRegisterDate(register_date_);
        cCar.setIssueDate(issue_date_);
        cCar.setPlateNum(map.getOrDefault("plate_num", "").toString());
        cCar.setModel(map.getOrDefault("model", "").toString());
        cCar.setOwner(map.getOrDefault("owner", "").toString());
        cCar.setVin(map.getOrDefault("vin", "").toString());
        cCar.setAddr(map.getOrDefault("addr", "").toString());
        cCar.setVehicleType(map.getOrDefault("vehicle_type", "").toString());
        cCar.setEngineNum(map.getOrDefault("engine_num", "").toString());
        cCar.setOfficialSeal(map.getOrDefault("official_seal", "").toString());
        cCar.setTotalQuality(map.getOrDefault("total_quality", "").toString());
        cCar.setUseCharacter(map.getOrDefault("use_character", "").toString());
        cCar.setLeadQuality(map.getOrDefault("lead_quality", "").toString());
        cCar.setOverallSize(map.getOrDefault("overall_size", "").toString());
        cCar.setPassengersNum(map.getOrDefault("passengers_num", "").toString());
        cCar.setPrepareQuality(map.getOrDefault("prepare_quality", "").toString());
        cCar.setRecord(map.getOrDefault("record", "").toString());
        cCar.setRemarks(map.getOrDefault("remarks", "").toString());
        cCar.setAxleCount(map.getOrDefault("axle_count", "").toString());
        cCar.setLoadQuality(map.getOrDefault("load_quality", "").toString());
        cCar.setLoadCapacity(map.getOrDefault("load_capacity", "").toString());*/


        return AjaxResult.success("创建失败");
    }


    @ApiOperation("获取车辆信息")
    @GetMapping("/getCarInfo")
    public AjaxResult getCarInfo(@ApiParam(value = "userId", required = true) Integer userId) {
        CUser cUser = userService.selectCUserByUserId(userId);
        if (cUser == null || cUser.getCarId() == null) {
            return AjaxResult.error("用户不存在");
        }

        CCar cCar = carService.selectCCarByCarId(cUser.getCarId());
        if (cUser.getCarId() == 0) {
            return AjaxResult.error("车辆不存在");
        }

        Map<String, Object> ajaxResult = new HashMap<>();
        ajaxResult.put("car_id", cCar.getCarId());
        ajaxResult.put("model", cCar.getModel());
        ajaxResult.put("picture", cCar.getPicture());
        ajaxResult.put("Permit", cCar.getPermit());
        ajaxResult.put("Permit_b", cCar.getPermitB());
        ajaxResult.put("owner", cCar.getOwner());
        ajaxResult.put("vin", cCar.getVin());
        ajaxResult.put("addr", cCar.getAddr());
        ajaxResult.put("vehicle_type", cCar.getVehicleType());
        ajaxResult.put("use_character", cCar.getUseCharacter());
        ajaxResult.put("engine_num", cCar.getEngineNum());
        ajaxResult.put("official_seal", cCar.getOfficialSeal());
        ajaxResult.put("issue_date", cCar.getIssueDate());
        ajaxResult.put("register_date", cCar.getRegisterDate());
        ajaxResult.put("file_number", cCar.getFileNumber());
        ajaxResult.put("total_quality", cCar.getTotalQuality());
        ajaxResult.put("lead_quality", cCar.getLeadQuality());
        ajaxResult.put("load_quality", cCar.getLoadQuality());
        ajaxResult.put("overall_size", cCar.getOverallSize());
        ajaxResult.put("passengers_num", cCar.getPassengersNum());
        ajaxResult.put("prepare_quality", cCar.getPrepareQuality());
        ajaxResult.put("record", cCar.getRecord());
        ajaxResult.put("remarks", cCar.getRemarks());
        ajaxResult.put("axle_count", cCar.getAxleCount());
        ajaxResult.put("load_capacity", cCar.getLoadCapacity());
        ajaxResult.put("create_by", cCar.getCreateBy());
        ajaxResult.put("create_time", cCar.getCreateTime());
        ajaxResult.put("update_by", cCar.getUpdateBy());
        ajaxResult.put("update_time", cCar.getUpdateTime());
        ajaxResult.put("is_delete", cCar.getIsDelete());
        ajaxResult.put("status", cCar.getStatus());
        ajaxResult.put("plate_num", cCar.getPlateNum());

        return AjaxResult.success(ajaxResult);
    }


}
